package top.xzxsrq.fileviewutils.security;

import org.h2.server.web.WebServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.security.web.firewall.StrictHttpFirewall;
import top.xzxsrq.fileviewutils.mapper.TokensAreDiscardedMapper;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    // 自定义密码加密配置常用的BCryptPasswordEncoder，也可以用其他的
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 注入h2控制台被允许访问
     *
     * @return
     */
    @Bean
    public ServletRegistrationBean h2servletRegistration() {
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(new WebServlet());
        registrationBean.addUrlMappings("/h2-console/*");
        //允许远程访问h2-console
        registrationBean.addInitParameter("webAllowOthers", "");
        registrationBean.addInitParameter("trace", "");
        return registrationBean;
    }

    @Bean
    public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
        // 第二种：自定义防火墙规则，放行分号；
        StrictHttpFirewall firewall = new StrictHttpFirewall();
        firewall.setAllowSemicolon(true);
        firewall.setAllowUrlEncodedSlash(true);// 放行斜杠(%2f或者%2F)
        firewall.setAllowBackSlash(true); //放行反斜杠(\或者%5c或者%5B)
        firewall.setAllowUrlEncodedPercent(true); //放行百分号(URL编码后为%25)
        firewall.setAllowUrlEncodedPeriod(true); //放行英文句号.(%2e或者%2E)
        return firewall;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
        // 同时在Websecurity中配置此bean
        web.httpFirewall(allowUrlEncodedSlashHttpFirewall());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers().frameOptions().sameOrigin(); // 允许来自同一来源的H2 控制台的请求
        http.csrf().ignoringAntMatchers("/h2-console/**"); // 禁用 H2 控制台的 CSRF 防护
        http
                // 关闭csrf
                .csrf().disable()
                // 不通过session 获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 放行所有的HttpMethod.OPTIONS请求
                .antMatchers(HttpMethod.OPTIONS, "/**/*").permitAll()
                // 配置静态资源可以访问
                .antMatchers("/", "/index", "/index.html").permitAll()
                .antMatchers("/pagePlugin/**/*", "/static/**/*").permitAll()
                .antMatchers("/app-loading.css", "/favicon.ico").permitAll()
                // h2控制台放开拦截
                .antMatchers("/h2-console/**").permitAll()
                // 插件测试使用
                .antMatchers("/PluginTest/**").permitAll()
                // 文件下载
                .antMatchers("/file/downloadFileOrDirById").permitAll()
                .antMatchers("/file/getShareFile").permitAll()
                .antMatchers("/file/shareFileDown").permitAll()
                // 存放jar的文件夹不让使用
                .antMatchers("/jarPlugin/**").denyAll()
//                // 开放登录接口 JWTAuthenticationFilter 在这里已经拦截实现，不用管了
//                .antMatchers("/user/login").permitAll()
                // 其他请求都需要认证
                .anyRequest().authenticated();
//                 添加JWT登录拦截器
        http.addFilter(new JWTAuthenticationFilter(authenticationManager()));
        // 添加JWT鉴权拦截器
        http.addFilterBefore(new JWTAuthorizationFilter(authenticationManager(), tokensAreDiscardedMapper),
                UsernamePasswordAuthenticationFilter.class);
        // 认证授权异常自定义处理
        http.exceptionHandling()
                // 匿名用户访问无权限资源时的异常
                .authenticationEntryPoint(new JWTAuthenticationEntryPoint());
        // 跨域请求配置
        http.cors();
    }

    @Autowired
    private TokensAreDiscardedMapper tokensAreDiscardedMapper;


}
